package com.egdigital.allzic.ui.activity;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.android.volley.VolleyError;
import com.egdigital.allzic.R;
import com.egdigital.allzic.adswizz.AdsHttpRequest;
import com.egdigital.allzic.adswizz.OnXMLDownloadListener;
import com.egdigital.allzic.adswizz.XMLDownloader;
import com.egdigital.allzic.adswizz.XMLHandler;
import com.egdigital.allzic.data.json.JsonCacheManager;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserSong;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Song;
import com.egdigital.allzic.data.object.Station;
import com.egdigital.allzic.service.Scheduler;
import com.egdigital.allzic.service.Scheduler.Mode;
import com.egdigital.allzic.service.Scheduler.OnScheduleTimeListener;
import com.egdigital.allzic.service.ServiceStreaming;
import com.egdigital.allzic.utils.ImageManager;
import com.egdigital.allzic.utils.NetworkManager;
import com.egdigital.allzic.utils.PrefManager;
import com.egdigital.allzic.utils.Utils;

public class ActivityPlayerNew extends SherlockFragmentActivity implements OnClickListener {

	private static final String		TAG						= ActivityPlayerNew.class.getSimpleName();
	// download songs data
	private static final String		ADSWIZZ_REQUEST_ONE		= "http://deliveryengine.espacegroup.adswizz.com/swfIndex?reqType=AdsSetup&protocolVersion=2.0&zoneId=113&companionZones=114";
	private static final int		SCHEDULER_SONG_DL		= 15000;
	private JsonParserSong			mJsonParserSong;
	private Scheduler				mSongScheduler;
	private XMLDownloader 			mDownloader;
	private ImageManager			mImageManager;
	// song
	private Song					mSong;
	private TextView				mTitle;
	private TextView				mArtist;
	private ImageView				mImage;
	private FrameLayout				mAlbumLayout;
	// audio
	private AudioManager			mAudioManager;
	private int						mVolume;
	private int						mMaxVolume;
	private ImageButton				mSoundToggle;
	private SeekBar					mSeekBarVolume;
	// config streaming
	public static final String		STATION					= "station";
	public static final String		SHOULD_PLAY				= "play";
	private boolean					mOnBackResult			= false;
	private boolean					mShouldPlay				= true;
	private ServiceStreaming		mServiceRadio;
	private Station					mStation;
	private ProgressBar				mPlayerLoading;
	// download progress
	protected LinearLayout			mLoadingStreamingView;
	// sharing
	private ImageButton				mFacebook;
	private ImageButton				mTwitter;
	private ImageButton				mFavorite;
	// ui player
	private ImageButton				mPlayButton;
	private ImageView				mLogoStation;
	private TextView				mStationTitle;
	private TextView				mStationDesc;
	private RelativeLayout			mDescriptionLayout;
	// pub
	private ImageView				mViewAdsWizz;
	final private BroadcastReceiver	mPlayBackReceiver		= new BroadcastReceiver() {

																@Override
																public void onReceive(Context context, Intent intent) {
																	String actionString = intent.getAction();
																	Log.w(TAG, "" + actionString);
																	// get mode pub/radio
																	if (actionString == ServiceStreaming.SERVICE_PLAY) {
																		setUiIsPlaying();
																		mOnBackResult = true;
																	} else if (actionString == ServiceStreaming.SERVICE_STOP) {
																		AdsHttpRequest.getInstance().cancelGetTask();
																		setUiIsStopped();
																		mOnBackResult = false;
																	} else if (actionString == ServiceStreaming.SERVICE_LOADING) {
																	} else if (actionString == ServiceStreaming.SERVICE_ERROR) {
																		AdsHttpRequest.getInstance().cancelGetTask();
																		setUiIsPlaying();
																		mOnBackResult = false;
																	} else if (actionString == ServiceStreaming.SERVICE_KILLED) {
																		AdsHttpRequest.getInstance().cancelGetTask();
																		mOnBackResult = false;
																		finish();
																	} else if (actionString == ServiceStreaming.SERVICE_PERCENT) {
																	} else if (actionString == ServiceStreaming.SERVICE_METADATA) { // adswiz 1.0
																		// PrefManager preferenceManager = PrefManager.getInstance(getApplicationContext());
																		// String key = intent.getExtras().getString(ServiceStreaming.SERVICE_METADATA + "_key");
																		// String value = intent.getExtras().getString(ServiceStreaming.SERVICE_METADATA + "_value");
																		// if (key != null) {
																		// if (key.equalsIgnoreCase("metadata")) {
																		// String substr = value.substring(value.indexOf("=") + 1);
																		// String url = String.format(AdswizzManager.URL_SERVER, getString(R.string.adswizz_zoneId_banner), substr);
																		// new GetHtml().execute(url);
																		// preferenceManager.addString_Pref("adswizz_context", substr);
																		// } else if (key.equalsIgnoreCase("durationMilliseconds")) {
																		// preferenceManager.addLong_pref("adswizz_duration", Long.parseLong(value));
																		// }
																		// }
																	} else {
																		AdsHttpRequest.getInstance().cancelGetTask();
																		mOnBackResult = false;
																		setUiIsStopped();
																	}
																}
															};
	private ServiceConnection		mServiceConnexionRadio	= new ServiceConnection() {

																@Override
																public void onServiceDisconnected(ComponentName name) {
																	mServiceRadio = null;
																}

																@Override
																public void onServiceConnected(ComponentName name, IBinder binder) {
																	if (mServiceRadio == null) {
																		mServiceRadio = (ServiceStreaming) ((ServiceStreaming.PlayerBinder) binder).getServiceInstance();
																	}
																	if (!ServiceStreaming.isPlayingRadio()) {
																		final PrefManager preferenceManager = PrefManager.getInstance(getApplicationContext());
																		startRadio(preferenceManager.getString_prefForKey(XMLHandler.MEDIA_FILE), mShouldPlay);
																	}
																}
															};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setVolumeControlStream(AudioManager.STREAM_MUSIC); // allow music volume
		setContentView(R.layout.activity_player);
		// actionbar
		ActionBar mActionBar = getSupportActionBar();
		mActionBar.setHomeButtonEnabled(false);
		mActionBar.setTitle(getString(R.string.activity_player_title));
		// views
		setupViews();
		try {
			// get the station to play
			Bundle bundle = getIntent().getExtras();
			mStation = (Station) bundle.getParcelable(STATION);
			mStationTitle.setText(Html.fromHtml(mStation.getmTitle()));
			mStationDesc.setText(Html.fromHtml(mStation.getmSubtitle()));
			mShouldPlay = bundle.getBoolean(SHOULD_PLAY);
		} catch (Exception e) {
		}
		// read more button
		final TextView tvDescription = (TextView) findViewById(R.id.activity_player_readmore);
		if (!Utils.isEllipsize(mStationDesc)) {
			mDescriptionLayout.setOnClickListener(this);
			SpannableString string = new SpannableString(getString(R.string.activity_player_more));
			string.setSpan(new UnderlineSpan(), 0, string.length(), 0);
			tvDescription.setText(string);
			ViewTreeObserver observer = tvDescription.getViewTreeObserver();
			observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

				@Override
				public void onGlobalLayout() {
					int maxLines = (int) tvDescription.getHeight() / tvDescription.getLineHeight();
					tvDescription.setMaxLines(maxLines);
					tvDescription.getViewTreeObserver().removeGlobalOnLayoutListener(this);
				}
			});
			tvDescription.setVisibility(View.VISIBLE);
		} else {
			tvDescription.setVisibility(View.GONE);
		}
		// click listener
		setupClickListener();
		// streaming loading progress display
		if (/* (mStartMode != null && mStartMode.equals(StreamingMode.PUB)) */mShouldPlay || ServiceStreaming.isloadingRadio()) {
			Log.d(TAG, "onCreate--loading");
			setUiIsLoading(true);
		} else if (ServiceStreaming.isPlayingRadio()) {
			Log.d(TAG, "onCreate--playing");
			setUiIsPlaying();
		} else {
			Log.d(TAG, "onCreate--stopped");
			setUiIsStopped();
		}
		// receivers
		setupReceivers();
		// audio
		setupControlVolume();
		// image
		setupImageLoader();
		// volley
		setupVolleyForSong();
		// song download
		setupSongScheduler();
		// adswizz
		setupAdsWizz();
		// streaming service
		bindServices();
		super.onCreate(savedInstanceState);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		getSupportMenuInflater().inflate(R.menu.menu_player, menu);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putParcelable("station", mStation);
	}

	@Override
	protected void onDestroy() {
		Utils.cancelToast();
		if (mPlayBackReceiver != null) {
			LocalBroadcastManager.getInstance(this).unregisterReceiver(mPlayBackReceiver);
		}
		// return result value
		Intent intent = new Intent();
		intent.putExtra("must_play", mOnBackResult);
		setResult(RESULT_OK, intent);
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		unbindServices();
		if (mSongScheduler != null) {
			mSongScheduler.stopTimer();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// favorites
		boolean isFavorite = JsonCacheManager.isStationSaved(mStation, getApplicationContext(), JsonCacheManager.FAVORITE_STATION);
		if (isFavorite) {
			mStation.isFavorite = 1;
			mFavorite.setSelected(true);
		} else {
			mStation.isFavorite = 0;
			mFavorite.setSelected(false);
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
		overridePendingTransition(R.anim.slide_from_behind, R.anim.slide_out_right);
	}

	@Override
	public void onClick(View view) {
		String sharerUrl = mStation.getmUrl();
		switch (view.getId()) {
			case R.id.activity_player_play: // play pause
				if (ServiceStreaming.isPlayingRadio()) {
					stopRadio();
				} else {
					startRadio("", true);
				}
				break;
			case R.id.activity_player_sound: // volume
				mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
				mSeekBarVolume.setProgress(0);
				mSoundToggle.setImageResource(R.drawable.sound_off);
				break;
			case R.id.activity_player_like: // Favorite
				mFavorite.setEnabled(false);
				if (mStation == null) {
					break;
				}
				if (mFavorite.isSelected()) {
					try {
						mStation.isFavorite = 0;
						JsonCacheManager.removeStation(getApplicationContext(), mStation, JsonCacheManager.FAVORITE_STATION);
						mFavorite.setSelected(false);
						Utils.customToast(new SpannableStringBuilder(getString(R.string.favorite_station_removed)), getApplicationContext(), false);
					} catch (IOException e1) {
					}
				} else {
					try {
						mStation.isFavorite = 1;
						JsonCacheManager.addStation(getApplicationContext(), mStation, JsonCacheManager.FAVORITE_STATION);
						mFavorite.setSelected(true);
						Utils.customToast(new SpannableStringBuilder(getString(R.string.favorite_station_added)), getApplicationContext(), false);
					} catch (IOException e) {
					}
				}
				Intent intent = new Intent("fav_modification");
				intent.putExtra("isStation", true);
				LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
				mFavorite.setEnabled(true);
				break;
			case R.id.activity_player_twitter: // twitter
				Intent tweetIntent = new Intent();
				tweetIntent.setPackage("com.twitter.android");
				tweetIntent.setAction(Intent.ACTION_SEND);
				tweetIntent.setType("text/plain");
				String text = String.format(getString(R.string.activity_player_twitter), mStation.getmTitle(), getString(R.string.url_allzic_site));
				tweetIntent.putExtra(Intent.EXTRA_TEXT, text);
				try {
					// tweetIntent.setType("image/png");
					// tweetIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://com.egdigital.allzic/drawable/icon"));
					startActivity(tweetIntent);
				} catch (Exception e) {
					Intent intentWeb = new Intent(Intent.ACTION_SEND);
					String url = "http://www.twitter.com/intent/tweet?url=" + text;
					intentWeb = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					startActivity(intentWeb);
				}
				break;
			case R.id.activity_player_facebook: // facebook
				try {
					Intent intent1 = new Intent();
					intent1.setPackage("com.facebook.katana");
					intent1.setAction(Intent.ACTION_SEND);
					intent1.setType("text/plain");
					intent1.putExtra(Intent.EXTRA_TEXT, getString(R.string.url_allzic_site));
					startActivity(intent1);
				} catch (Exception e) {
					// If we failed (not native FB app installed), try share through SEND
					Intent intent2 = new Intent(Intent.ACTION_SEND);
					sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + getString(R.string.url_allzic_site);
					intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
					startActivity(intent2);
				}
				break;
			case R.id.activity_player_pub: // adwizz
				Intent intent3 = new Intent(Intent.ACTION_SEND);
				final PrefManager preferenceManager = PrefManager.getInstance(getApplicationContext());
				intent3 = new Intent(Intent.ACTION_VIEW, Uri.parse(preferenceManager.getString_prefForKey(XMLHandler.COMPANION_CLICK_THROUGHT)));
				startActivity(intent3);
				break;
			case R.id.activity_player_description_layout:
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
				alertDialog.setPositiveButton(getString(R.string.activity_player_close), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// dismiss the dialog
					}
				});
				alertDialog.setTitle(getString(R.string.activity_player_desc));
				alertDialog.setMessage(Html.fromHtml(mStation.getmSubtitle()));
				alertDialog.setCancelable(true);
				alertDialog.show();
				break;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.action_close:
				finish();
				overridePendingTransition(R.anim.slide_from_behind, R.anim.slide_out_right);
				break;
		}
		return true;
	}

	/**
	 * Service management
	 */
	private void bindServices() {
		if (mServiceConnexionRadio != null) {
			bindService(new Intent(ActivityPlayerNew.this, ServiceStreaming.class), mServiceConnexionRadio, Context.BIND_AUTO_CREATE);
		}
	}

	private void unbindServices() {
		try {
			unbindService(mServiceConnexionRadio);
		} catch (Exception e) {
		}
	}

	public void startRadio(String urlAd, boolean shouldStart) {
		if (mStation == null || shouldStart == false) {
			return;
		}
		if (!NetworkManager.isConnected(getApplicationContext())) {
			Utils.customToast(new SpannableStringBuilder(getString(R.string.no_network)), getApplicationContext(), false);
			setUiIsStopped();
			return;
		} else if (!NetworkManager.isConnectedFast(getApplicationContext())) {
			Utils.customToast(new SpannableStringBuilder(getString(R.string.no_fast_network)), getApplicationContext(), false);
			setUiIsStopped();
			return;
		}
		setUiIsLoading(true);
		Intent intent = new Intent(ActivityPlayerNew.this, ServiceStreaming.class);
		intent.putExtra("station", mStation);
		intent.putExtra("pub", urlAd);
		intent.putExtra(SHOULD_PLAY, shouldStart);
		startService(intent);
	}

	private void stopRadio() {
		setUiIsLoading(false);
		mServiceRadio.stopStreaming();
	}

	/**
	 * volume control
	 */
	private void setVolume(int volume) {
		if (mAudioManager == null) {
			return;
		}
		mVolume = volume;
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
		if (volume == 0) {
			mSoundToggle.setImageResource(R.drawable.sound_off);
		} else {
			mSoundToggle.setImageResource(R.drawable.sound);
		}
	}

	private void setupControlVolume() {
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		mSeekBarVolume.setMax(mMaxVolume);
		mSeekBarVolume.setProgress(mVolume);
		mSeekBarVolume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				setVolume(progress);
			}
		});
		if (mVolume == 0) {
			mSoundToggle.setImageResource(R.drawable.sound_off);
		} else {
			mSoundToggle.setImageResource(R.drawable.sound);
		}
	}

	private void setupViews() {
		mPlayerLoading = (ProgressBar) findViewById(R.id.activity_player_progress);
		mViewAdsWizz = (ImageView) findViewById(R.id.activity_player_pub);
		mStationTitle = (TextView) findViewById(R.id.activity_player_radio_title);
		mFacebook = (ImageButton) findViewById(R.id.activity_player_facebook);
		mTwitter = (ImageButton) findViewById(R.id.activity_player_twitter);
		mFavorite = (ImageButton) findViewById(R.id.activity_player_like);
		mSoundToggle = (ImageButton) findViewById(R.id.activity_player_sound);
		mLogoStation = (ImageView) findViewById(R.id.activity_player_radio_thumb);
		mImage = (ImageView) findViewById(R.id.fragment_album_player_image);
		mArtist = (TextView) findViewById(R.id.fragment_player_artist_name);
		mTitle = (TextView) findViewById(R.id.fragment_player_music_title);
		mStationTitle = (TextView) findViewById(R.id.activity_player_radio_title);
		mStationDesc = (TextView) findViewById(R.id.activity_player_radio_description);
		mSeekBarVolume = (SeekBar) findViewById(R.id.activity_player_volume);
		mPlayButton = (ImageButton) findViewById(R.id.activity_player_play);
		mAlbumLayout = (FrameLayout) findViewById(R.id.player_album);
		mDescriptionLayout = (RelativeLayout) findViewById(R.id.activity_player_description_layout);
		mLoadingStreamingView = (LinearLayout) findViewById(R.id.fragment_player_loading_big);
	}

	private void setupClickListener() {
		mPlayButton.setOnClickListener(this);
		mSoundToggle.setOnClickListener(this);
		mFacebook.setOnClickListener(this);
		mTwitter.setOnClickListener(this);
		mFavorite.setOnClickListener(this);
		mViewAdsWizz.setOnClickListener(this);
	}

	private void setupImageLoader() {
		mImageManager = new ImageManager(getApplicationContext());
		mImageManager.setOptions();
		mImageManager.setImageLoader();
		try {
			Utils.setImageFromUrl(mImageManager, mStation.getmThumbMobile(), mLogoStation);
		} catch (Exception e) {
			Utils.setImageFromUrl(mImageManager, mStation.getmThumb(), mLogoStation);
		}
	}

	private void setupReceivers() {
		LocalBroadcastManager.getInstance(this).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_PLAY));
		LocalBroadcastManager.getInstance(this).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_STOP));
		LocalBroadcastManager.getInstance(this).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_LOADING));
		LocalBroadcastManager.getInstance(this).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_PERCENT));
		LocalBroadcastManager.getInstance(this).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_METADATA));
		LocalBroadcastManager.getInstance(this).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_ERROR));
		LocalBroadcastManager.getInstance(this).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_KILLED));
	}

	/**
	 * start data downloads
	 */
	private void loadData() {
		if (NetworkManager.isConnected(getApplicationContext())) {
			mJsonParserSong.extractJsonObjectData(mStation.getmPlaylist());
		}
	}

	/**
	 * loading album image wih a timer
	 */
	private void setupSongScheduler() {
		mSongScheduler = new Scheduler(SCHEDULER_SONG_DL, -1, Scheduler.Mode.ASC);
		mSongScheduler.setOnScheduleTimeListener(new OnScheduleTimeListener() {

			@Override
			public void onScheduleTime(int count) {
				loadData();
			}
		});
		mSongScheduler.startTimer();
	}

	/**
	 * volley callbacks for song info download
	 */
	private void setupVolleyForSong() {
		if (mJsonParserSong == null) {
			mJsonParserSong = JsonParserSong.getInstance();
			VolleyManager.init(this);
			mJsonParserSong.initAndStartRequestQueue();
			mJsonParserSong.setJsonCallBack(new JsonCallBack() {

				@Override
				public void downloadStarted() {
					// nope nope nope
				}

				@Override
				public void downloadPercent(int percent) {
					// nope nothing
				}

				@Override
				public <T> void downloadCompleted(List<T> list) {
					if (list == null) {
						return;
					}
					if (!list.isEmpty()) {
						mSong = (Song) list.get(0);
						Utils.setImageFromUrl(mImageManager, mSong.getmCover(), mImage);
						mTitle.setText(mSong.getmTitle());
						mArtist.setText(mSong.getmArtiste());
					}
				}

				@Override
				public void downloadEndedWithError(VolleyError error) {
					// nope here either
				}
			});
		}
	}

	/**
	 * adswizz
	 */
	private void setupAdsWizz() {
		mDownloader = new XMLDownloader(ADSWIZZ_REQUEST_ONE, new OnXMLDownloadListener() {

			@Override
			public void OnDownloadFinish(final HashMap<String, String> data) {
				if (data != null) {
					// preference save
					final PrefManager preferenceManager = PrefManager.getInstance(getApplicationContext());
					try {
						preferenceManager.addStringMap_prefs(data);
					} catch (Exception e) {
					}
					if (preferenceManager.getString_prefForKey(XMLHandler.COMPANION_ADS_TYPE).equals(XMLHandler.COMPANION_ADS_BANNER)) {
						try {
							Utils.setImageFromUrl(mImageManager, preferenceManager.getString_prefForKey(XMLHandler.COMPANION_IMAGE), mViewAdsWizz);
						} catch (Exception e) {
						}
					} else if (preferenceManager.getString_prefForKey(XMLHandler.COMPANION_ADS_TYPE).equals(XMLHandler.COMPANION_ADS_INTERSTITIAL)) {
						openAdsWizzInterstitial(preferenceManager.getString_prefForKey(XMLHandler.COMPANION_IMAGE), preferenceManager.getString_prefForKey(XMLHandler.COMPANION_CLICK_THROUGHT));
					}
				}
			}

			@Override
			public void OnDownloadNoNetwork() {
			}

			@Override
			public void OnDownloadFailed() {
			}
		});
		mDownloader.execute(getApplicationContext());
	}

	private void openAdsWizzInterstitial(String urlImage, final String urlClick) {
		LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.view_adswizz_interstitial, null);
		RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.adswizz_pub);
		ImageView image = (ImageView) view.findViewById(R.id.adswizz_image);
		final ImageButton button = (ImageButton) view.findViewById(R.id.adswizz_close);
		final TextView textCount = (TextView) view.findViewById(R.id.adswizz_count);
		//
		final Dialog dialog = new Dialog(ActivityPlayerNew.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(layout);
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(R.color.clr_trans_dark_grey));
		dialog.setCanceledOnTouchOutside(false); // Gingerbread support
		dialog.setCancelable(false);
		//
		Window window = dialog.getWindow();
		WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
		windowLayoutParams.gravity = Gravity.CENTER;
		window.setAttributes(windowLayoutParams);
		dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		//
		// count schedule
		//
		PrefManager preferenceManager = PrefManager.getInstance(getApplicationContext());
		int duration = preferenceManager.getInt_prefForKey(XMLHandler.MEDIA_FILE_DURATION);
		final Scheduler scheduler = new Scheduler(1000, 5, Mode.DESC);
		scheduler.setOnScheduleTimeListener(new OnScheduleTimeListener() {

			@Override
			public void onScheduleTime(int count) {
				textCount.setText(count + " " + getString(R.string.adswizz_count));
				if (count == 0) {
					// mStartMode = StreamingMode.RADIO;
					dialog.dismiss();
				}
			}
		});
		scheduler.startTimer();
		//
		layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				adswizzClickIntent(urlClick);
			}
		});
		try {
			Utils.setImageFromUrl(mImageManager, preferenceManager.getString_prefForKey(XMLHandler.COMPANION_IMAGE), image);
		} catch (Exception e) {
		}
		try {
			dialog.show();
		} catch (Exception e) {
		}
	}

	private boolean adswizzClickIntent(String url) {
		if (!url.startsWith("http://") && !url.startsWith("https://")) {
			url += "http://";
		}
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse(url));
			startActivity(intent);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	/**
	 * processing stream ui update
	 */
	private void setUiIsPlaying() {
		setUiStreamingLoaded();
		mPlayerLoading.setVisibility(View.GONE);
		mPlayButton.setVisibility(View.VISIBLE);
		mPlayButton.setImageDrawable(getResources().getDrawable(R.drawable.selector_btn_stop));
		mPlayButton.setEnabled(true);
	}

	private void setUiIsStopped() {
		setUiStreamingLoaded();
		mPlayerLoading.setVisibility(View.GONE);
		mPlayButton.setVisibility(View.VISIBLE);
		mPlayButton.setImageDrawable(getResources().getDrawable(R.drawable.selector_btn_play));
		mPlayButton.setEnabled(true);
	}

	private void setUiIsLoading(boolean isStarting) {
		if (isStarting) {
			setUiStreamingLoading();
		}
		mPlayButton.setEnabled(false);
		mPlayButton.setVisibility(View.GONE);
		mPlayerLoading.setVisibility(View.VISIBLE);
	}

	/**
	 * loading stream progress bar display
	 */
	private void setUiStreamingLoading() {
		mAlbumLayout.setVisibility(View.GONE);
		mLoadingStreamingView.setVisibility(View.VISIBLE);
	}

	private void setUiStreamingLoaded() {
		mLoadingStreamingView.setVisibility(View.GONE);
		mAlbumLayout.setVisibility(View.VISIBLE);
	}
}
